package com.leo.nio.filechannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author du
 */
public class NioFileChannelFromFile {

    public static void main(String[] args) throws IOException {
        File file = new File("d:\\file01.txt");

        // 1.从文件获取输入流
        FileInputStream fileInputStream = new FileInputStream(file);

        // 2.从输入流获取通道
        FileChannel fileChannel = fileInputStream.getChannel();

        // 3.创建ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate((int) file.length());

        // 4.读取ByteBuffer中的数据并显示
        while(-1 != fileChannel.read(byteBuffer)) {
            System.out.println(new String(byteBuffer.array()));
        }

        // 5.关闭输入流
        fileInputStream.close();
    }
}
